package com.chinapost.service.impl;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinapost.dao.BaseDaoI;
import com.chinapost.excelUtil.DateUtil;
import com.chinapost.excelUtil.ExcelUtil;
import com.chinapost.po.Tdept;
import com.chinapost.po.Twdsb;
import com.chinapost.po.Tuser;
import com.chinapost.po.Twdxx;
import com.chinapost.service.WdsbServiceI;
import com.chinapost.vo.DataGrid;
import com.chinapost.vo.Wdsb;

@Service("wdsbService")
public class WdsbServiceImpl implements WdsbServiceI {

	@Autowired
	private BaseDaoI<Twdsb> wdsbDao;
	@Autowired
	private BaseDaoI<Tdept> deptDao;
	@Autowired
	private BaseDaoI<Twdxx> wdxxDao;
	@Autowired
	private BaseDaoI<Tuser> userDao;

	@Override
	public DataGrid datagrid(Wdsb wdsb) {
		DataGrid dg = new DataGrid();
		dg.setRows(listRows(find(wdsb)));
		dg.setTotal(total(wdsb));
		return dg;
	}

	private Long total(Wdsb wdsb) {
		String hql = "select count(*) from Twdsb t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(wdsb, hql, params);
		return wdsbDao.count(hql, params);
	}

	private List<Twdsb> find(Wdsb wdsb) {
		String hql = "from Twdsb t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(wdsb, hql, params);
		if (wdsb.getOrder() != null && wdsb.getSort() != null) {
			hql += " order by " + wdsb.getSort() + " " + wdsb.getOrder();
		}
		return wdsbDao.find(hql, params, wdsb.getPage(), wdsb.getRows());
	}

	private List<Wdsb> listRows(List<Twdsb> lt) {
		List<Wdsb> rows = new ArrayList<Wdsb>();
		if (lt != null && lt.size() > 0) {
			for (Twdsb t : lt) {
				Wdsb sub = new Wdsb();
				BeanUtils.copyProperties(t, sub);
				sub.setDeptId(t.getTdept().getCid());
				sub.setDeptName(t.getTdept().getCname());
				sub.setWdid(t.getTwdxx().getCid());
				sub.setWdname(t.getTwdxx().getCname());
				rows.add(sub);
			}
		}
		return rows;
	}

	private String addWhere(Wdsb wdsb, String hql, Map<String, Object> params) {
		if (wdsb != null && wdsb.getCid() != null && !wdsb.getCid().trim().equals("")) {
			hql += " and t.cid = :id ";
			params.put("id", wdsb.getCid());
		}
		if (wdsb != null && wdsb.getWdname() != null && !wdsb.getWdname().trim().equals("")) {
			hql += " and t.twdxx.cname like :wdname ";
			params.put("wdname", "%%" + wdsb.getWdname() + "%%");
		}
		if (wdsb != null && !StringUtils.isEmpty(wdsb.getWdid())) {
			hql += " and t.twdxx.cid = :wdid";
			params.put("wdid", wdsb.getWdid());
		}
		if (wdsb != null && wdsb.getDeptIds() != null && wdsb.getDeptIds().size() > 0) {
			hql += " and t.tdept.cid in(:deptids)";
			params.put("deptids", wdsb.getDeptIds());
		}
		return hql;
	}

	@Override
	public List<Wdsb> listWdsb() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void add(Wdsb wdsb) {
		Twdsb twdsb = new Twdsb();
		Date d = new Date();
		BeanUtils.copyProperties(wdsb, twdsb);
		twdsb.setCid(UUID.randomUUID().toString());
		twdsb.setCcreatedate(new Timestamp(d.getTime()));
		twdsb.setCmodifydate(new Timestamp(d.getTime()));
		twdsb.setTdept(deptDao.get(Tdept.class, wdsb.getDeptId()));
		twdsb.setTwdxx(wdxxDao.get(Twdxx.class, wdsb.getWdid()));
		if (!StringUtils.isEmpty(wdsb.getCreateUserId())) {
			twdsb.setTuserByCcreateuserid(userDao.get(Tuser.class, wdsb.getCreateUserId()));
			twdsb.setTuserByCmodifyuserid(userDao.get(Tuser.class, wdsb.getCreateUserId()));
		}
		wdsbDao.save(twdsb);
	}

	@Override
	public void edit(Wdsb wdsb) {
		Twdsb t = wdsbDao.get(Twdsb.class, wdsb.getCid());
		BeanUtils.copyProperties(wdsb, t, new String[] { "ccreatedate" });
		Date d = new Date();
		t.setCmodifydate(new Timestamp(d.getTime()));
		t.setTdept(deptDao.get(Tdept.class, wdsb.getDeptId()));
		t.setTwdxx(wdxxDao.get(Twdxx.class, wdsb.getWdid()));
		if (!StringUtils.isEmpty(wdsb.getModifyUserId())) {
			t.setTuserByCmodifyuserid(userDao.get(Tuser.class, wdsb.getModifyUserId()));
		}
	}

	@Override
	public void delete(Wdsb wdsb) {
		String cids = "";
		if (wdsb.getIds() != null) {
			String ids = wdsb.getIds();
			for (String cid : ids.split(",")) {
				cids += "'" + cid + "'" + ",";
			}
			cids = cids.substring(0, cids.length() - 1);
			String hql = "delete Twdsb t where t.cid in (" + cids + ")";
			wdsbDao.executeHql(hql);
		}

	}

	@Override
	public int addWdsbs(Wdsb wdsb) {
		int i = 0;
		String[] fields = { "wdname","cname","ctype","csyrq","czjnx","cyz","cyzj","cbz" };
		if (wdsb != null && !wdsb.getFilename().isEmpty()) {
			ExcelUtil eu = new ExcelUtil();
			List<ArrayList<String>> wdsbList = eu.read(wdsb.getFilename());
			Tdept tdept = deptDao.get(Tdept.class, wdsb.getDeptId());
			if (tdept != null) {
				for (ArrayList<String> row : wdsbList) {
					String wdname = row.get(0).trim();
					if (!StringUtils.isEmpty(wdname)) {
						String hql = "from Twdxx t where t.cname = :wdname";
						Map<String, Object> params = new HashMap<String, Object>();
						params.put("wdname", wdname);
						Twdxx wd = wdxxDao.get(hql, params);
						if (wd != null) {
							Twdsb t = new Twdsb();
							t.setCid(UUID.randomUUID().toString());
							t.setTdept(tdept);
							t.setTwdxx(wd);
							Date d = new Date();
							t.setCcreatedate(new Timestamp(d.getTime()));
							t.setCmodifydate(new Timestamp(d.getTime()));
							for (int n = 1; n < row.size(); n++) {
								try {
									if (n != 3) {
										org.apache.commons.beanutils.BeanUtils.setProperty(t, fields[n], row.get(n).trim());
									} else {
										t.setCsyrq(new Timestamp(DateUtil.parse4yMd(row.get(3).trim()).getTime()));
									}
								} catch (IllegalAccessException e) {
									e.printStackTrace();
								} catch (InvocationTargetException e) {
									e.printStackTrace();
								}
							}
							if (!StringUtils.isEmpty(wdsb.getCreateUserId())) {
								t.setTuserByCcreateuserid(userDao.get(Tuser.class, wdsb.getCreateUserId()));
								t.setTuserByCmodifyuserid(userDao.get(Tuser.class, wdsb.getCreateUserId()));
							}
							wdsbDao.save(t);
							i++;
						}
					}
				}
			}
			File f = new File(wdsb.getFilename());
			if (f.exists() && f.isFile()) {
				f.delete();
			}
		}
		return i;
	}

}
